<?php

class Application_Business_Abstract {
	
	/**
	 * Retorna um objeto da instância instance conforme id inserido
	 * @param string $instance
	 * @param int $id
	 * @throws Exception
	 * @return Model|NULL
	 */
	public function searchById($instance, $id){
		try {
			$model = new $instance();
			$result = $model->find($id)->toArray();
			
			if (count($result)) {
				$model->populate($result[0]);
				return $model;
			} else {
				return null;
			}
		} catch (Exception $e) {
			throw $e;
		}
	}
	
	/**
	 * Retorna array de objetos da instância instance conforme query
	 * @param string $instance
	 * @param array $filters ('field' => 'column', 'type' => 'operator', 'value' => 'value')
	 * @param array $order
	 * @param int $limit
	 * @param int $offset
	 * @throws Exception
	 * @return array Model
	 */
	public function search($instance, $filters = null, $order = null, $limit = null, $offset = null) {
		try {
			$model = new $instance();			
			$select = $model->select();
			
			if (isset($filters)) {
				foreach ($filters as $filter) {
					$select->where("{$filter['field']} {$filter['type']} ?", $filter['value']);
				}
			}

			$db = $model->getAdapter();
			$select->order($order)->limit($limit, $offset);
			$results = $db->fetchAll($select);

			$result = array();
			
			foreach ($results as $row) {
				array_push($result, new $instance($row));
			}
					
			return $result;
		} catch (Exception $e) {
			throw $e;
		}
	}
	
	/**
	 * Método que insere ou atualiza um 
	 * @param string $instance
	 * @param array $data
	 * @return int|string
	 */
	public function save($instance, $data) {
		$model = new $instance($data);
		$db = $model->getAdapter();
		
		try {
			$id = $model->getPrimaryKey();
			
			if (isset($id)) {
				$model->update($data, array(
					'id = ?' => $model->getPrimaryKey()
				));
			} else {
				$id = $model->insert($data);
			}
			
			return $id;
		}
		catch (Exception $e) {
			return $e->getMessage();
			
			if ($db->isConnected()) {
				$db->closeConnection();
			}
		}
	}	
	
	/**
	 * Executa um comando SQL no banco, procure utilizar em transações
	 * @param Business $adapter
	 * @param string $sql
	 * @return boolean
	 */
	public function execute($sql) {
		if (isset($this->db)) {
			try {
				$this->db->query($sql);
				return true;
			} catch (Exception $e) {
				echo $e->getMessage();
				return false;
			}			
		} else {
			return false;
		}
	}
}